package com.rainng.coursesystem.manager.member;

import com.rainng.coursesystem.dao.EventDAO;
import com.rainng.coursesystem.dao.MemberEventDAO;
import com.rainng.coursesystem.dao.MemberDAO;
import com.rainng.coursesystem.manager.BaseManager;
import com.rainng.coursesystem.model.bo.MemberEventSelectItemBO;
import com.rainng.coursesystem.model.entity.EventEntity;
import com.rainng.coursesystem.model.entity.MemberEventEntity;
import com.rainng.coursesystem.model.entity.MemberEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class EventSelectManager extends BaseManager {
    private final EventDAO eventDAO;
    private final MemberDAO memberDAO;
    private final MemberEventDAO memberEventDAO;

    public EventSelectManager(EventDAO eventDAO, MemberDAO memberDAO, MemberEventDAO memberEventDAO) {
        this.eventDAO = eventDAO;
        this.memberDAO = memberDAO;
        this.memberEventDAO = memberEventDAO;
    }

    public Integer getPageCount(Integer memberId, String eventName, String leaderName) {
        Integer areaId = memberDAO.getAreaIdById(memberId);
        Integer number = memberDAO.getBudgetById(memberId);
        return calcPageCount(eventDAO.countMemberCanSelect(areaId, memberId, number, eventName, leaderName), MemberEventDAO.PAGE_SIZE);
    }

    public List<MemberEventSelectItemBO> getPage(Integer index, Integer memberId, String eventName, String leaderName) {
        Integer areaId = memberDAO.getAreaIdById(memberId);
        Integer number = memberDAO.getBudgetById(memberId);
        return eventDAO.getMemberCanSelectPage(index, areaId, memberId, number, eventName, leaderName);
    }

    public EventEntity getEventById(Integer eventId) {
        return eventDAO.get(eventId);
    }

    public MemberEntity getMemberById(Integer memberId) {
        return memberDAO.get(memberId);
    }

    public boolean inSameArea(Integer eventId, Integer memberId) {
        return eventDAO.getAreaIdById(eventId)
                .equals(memberDAO.getAreaIdById(memberId));
    }

    public MemberEventEntity getMemberEventByEventIdAndMemberId(Integer eventId, Integer memberId) {
        return memberEventDAO.getByEventIdAndMemberId(eventId, memberId);
    }

    public Integer getMemberBudgetById(Integer memberId) {
        return memberDAO.getBudgetById(memberId);
    }

    @Transactional
    public int create(MemberEventEntity entity) {
        eventDAO.increaseSelectedCount(entity.getEventId());
        return memberEventDAO.insert(entity);
    }

    public int countMemberEventSelectedByTimePart(Integer memberId, String timePart) {
        return memberEventDAO.countMemberEventSelectedByTimePart(memberId, timePart);
    }
}
